package com.sacc.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sacc.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;


/**
 * @author 滚~韬
 * @date 2022/4/29 16:57
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    //匹配路径的工具类
    private final AntPathMatcher antPathMatcher =new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        //获取请求路径
        String path = request.getURI().getPath();
        log.info("请求路径: {}",path);
        if(antPathMatcher.match("/**/login/**",path)){
            return chain.filter(exchange);
        }
        else if(antPathMatcher.match("/**/callback/**",path)){
            return chain.filter(exchange);
        }
        List<String> tokens = request.getHeaders().get("token");
        //检验token是否存在
        if (tokens == null || StringUtils.isEmpty(tokens)){
            HashMap<String,Object> hashMap = new HashMap<>();
            hashMap.put("错误信息","token码未携带");
            DataBuffer wrap = exchange.getResponse().bufferFactory().wrap(JSON.toJSONString(hashMap).getBytes(StandardCharsets.UTF_8));
            log.error("请求未携带token");
            return exchange.getResponse().writeWith(Mono.just(wrap));
        }
        if(request.getHeaders().get("token").get(0).equals("gwtnb") ||
                JwtUtil.verify(request.getHeaders().get("token").get(0))){
            return chain.filter(exchange);
        }else {
            HashMap<String,Object> hashMap = new HashMap<>();
            hashMap.put("错误信息","token码错误");
            DataBuffer wrap = exchange.getResponse().bufferFactory().wrap(JSON.toJSONString(hashMap).getBytes(StandardCharsets.UTF_8));
            log.error("token码错误");
            return exchange.getResponse().writeWith(Mono.just(wrap));
        }
    }

    @Override
    public int getOrder() {
        return -2;
    }
}
